/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  ZoneTuiJianFragment.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-6 上午10:47:48   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.Type;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.jauker.widget.BadgeView;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.zone.ZoneQunZuBean;
import com.jiyi.bean.zone.ZoneQunZuListJson;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.QunZuListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DateUtils;
import com.swift.utils.DeviceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: ZoneTuiJianFragment
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-6 上午10:47:48
 * 
 */
public class ZoneQunZuFragment extends Fragment implements OnRefreshListener,
		OnScrollListener {

	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	@BindView(R.id.mainList)
	ListView mainList;
	@BindView(R.id.rlNew)
	RelativeLayout rlNew;

	@BindView(R.id.tvNull1)
	TextView tvNull1;
	@BindView(R.id.tvNull2)
	TextView tvNull2;

	@BindView(R.id.ivCreate)
	ImageView ivCreate;

	// 是否刷新模式
	boolean isRefresh = false;
	int pageNo = 1;// 页码
	private final int LOAD_DATA = 5; // 加载数据事件
	private boolean loadfinish = true; // 指示数据是否加载完成
	private boolean isLastRow = true; // 是否最后一行

	CommonAdapter<ZoneQunZuBean> mAdapter;
	List<ZoneQunZuBean> qunZuList = new ArrayList<ZoneQunZuBean>();

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_zone_qunzu, null, false);
		ButterKnife.bind(this, view);
		init();
		return view;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		ivCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.zone_new));
		ivCreate.animate()
				.translationY(0)
				.setInterpolator(new OvershootInterpolator(1.f))
				.setStartDelay(500)
				.setDuration(1000)
				.start();

	}

	@Subscribe
	public void onQunZuListEvent(QunZuListEvent qunZuListEvent) {
		int type = qunZuListEvent.type;
		Log.e("onQunZuListEvent " , " in   "+type);
		switch (type) {
		case QunZuListEvent.MY_QUNZU_FRAGMENT:
			Log.e("onQunZuListEvent " , QunZuListEvent.MY_QUNZU_FRAGMENT+"");
			refresh();
			break;

		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-7
	 */
	private void init() {
		setAdater();
		refresh();
	}

	/**
	 * @author: HYM
	 * @Title: setAdater
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-7
	 */
	private void setAdater() {
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mAdapter = new CommonAdapter<ZoneQunZuBean>(getActivity(), qunZuList,
				R.layout.item_zone_qunzu) {

			@Override
			public void convert(ViewHolder holder, final ZoneQunZuBean t) {
				holder.setImage(R.id.ivLogo, t.getGroup_head());
				holder.setOnClickListener(R.id.ivLogo, new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),
								ZoneQunZuInfoActivity.class);
						intent.putExtra("groupId", t.getId());
						startActivity(intent);
					}
				});
				holder.setText(R.id.tvQunZuName, t.getName());
				holder.setText(R.id.tvJoinNum, t.getMember() + "人");
				holder.setText(R.id.tvHuoDongNum, "发起活动：" + t.getActNum() + "次");
				if (!TextUtils.isEmpty(t.getAccess_time())) {
					holder.setVisible(R.id.tvDate, true);
					holder.setText(R.id.tvDate,
							DateUtils.convertTimeToFormat(t.getAccess_time()));
				} else {
					holder.setVisible(R.id.tvDate, false);
				}

				// holder.setBadge(R.id.ivCount, 6);
				// 复用之前的小红点控件
				BadgeView badgeView = (BadgeView) holder.getView(R.id.ivCount)
						.getTag();
				EMConversation conversation = EMClient.getInstance()
						.chatManager().getConversation(t.getHx_group_id());
				if (null != conversation) {
					int unReadCount = conversation.getUnreadMsgCount();
					if (unReadCount > 0) {
						if (badgeView == null) {
							badgeView = new BadgeView(getActivity());
						}
						badgeView.setVisibility(View.VISIBLE);
						badgeView.setTargetView(holder.getView(R.id.ivCount));
						badgeView.setBadgeGravity(Gravity.BOTTOM
								| Gravity.RIGHT);
						badgeView.setBadgeCount(unReadCount);
						holder.getView(R.id.ivCount).setTag(badgeView);
					} else {
						if (badgeView != null) {
							badgeView.setVisibility(View.GONE);
						}
					}
				}
			}
		};

		mainList.setAdapter(mAdapter);
		mainList.setOnScrollListener(this);
		mainList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ZoneQunZuBean ooo = (ZoneQunZuBean) parent.getAdapter().getItem(position);
				Intent intent2 = new Intent(getActivity(),EasemobChatActivity.class);
				intent2.putExtra(ClouldChatType.INTENT_USER_PIC,ooo.getGroup_head());
				intent2.putExtra("id", ooo.getId());
				intent2.putExtra("name", ooo.getName());
				intent2.putExtra("easemobgid", ooo.getHx_group_id());
				intent2.putExtra(ClouldChatType.INTENT_Group_Id,ooo.getId());
				intent2.putExtra("easeMobChatType", EaseConstant.CHATTYPE_GROUP);
				startActivity(intent2);

				// 把会话的消息清零
				EMConversation conversation = EMClient.getInstance()
						.chatManager().getConversation(ooo.getHx_group_id());
				if (null != conversation) {
					// 指定会话消息未读数清零
					conversation.markAllMessagesAsRead();
					mAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	@Override
	public void onRefresh() {
		refresh();
	}

	/**
	 * 作者：hym 日期：2017-4-6 描述：刷新数据
	 */
	void refresh() {
		isRefresh = true;
		pageNo = 1;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	/**
	 * 作者：hym 日期：2017-4-6 描述：加载更多数据
	 */
	void loadMore() {
		isLastRow = false;
		isRefresh = false;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	/**
	 * 处理中心
	 */
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_DATA:
				if (loadfinish) {
					loadfinish = false;
					getQunZuData();
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 判断是否滚到最后一行
		if (firstVisibleItem + visibleItemCount == totalItemCount
				&& totalItemCount > 0) {
			isLastRow = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case SCROLL_STATE_IDLE:
			// mAdapter.notifyDataSetChanged();// 提醒adapter更新
			if (isLastRow) {
				loadMore();
			}
			break;
		case SCROLL_STATE_TOUCH_SCROLL:

			break;
		case SCROLL_STATE_FLING:
			break;
		default:
			break;
		}

	}

	@OnClick({ R.id.ivCreate, R.id.rlNew })
	public void onClick(View view) {
		Intent intent ;
		switch (view.getId()) {
		case R.id.ivCreate:
			intent = new Intent(getActivity(), QunZuCreateActivity.class);
			int[] location = DeviceUtil.getInstance().getLocationOnScreen(ivCreate);
			int centerX = location[0];//获取当前位置的横坐标
			int centerY = location[1];//获取当前位置的纵坐标
			intent.putExtra("x",centerX);
			intent.putExtra("y",centerY);
			startActivity(intent);
			break;
		case R.id.rlNew:
			intent = new Intent(getActivity(), ZoneAllQunZuActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void getQunZuData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

		VolleyRequest.StringRequestPost(getContext(), WebApi.ZONE_QUNZU_LIST,
				"", params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ZoneQunZuListJson temp = new Gson().fromJson(
										result, ZoneQunZuListJson.class);
								if (temp != null && temp.getData().size() == 0) {
									refreshLayout.setVisibility(View.GONE);
									Spannable sTextSpannable = new SpannableString(
											tvNull1.getText());
									// 改变字体颜色
									sTextSpannable
											.setSpan(
													new ForegroundColorSpan(
															getResources()
																	.getColor(
																			R.color.tab_top_on)),
													5, 10, 0);
									tvNull1.setText(sTextSpannable);
									Spannable jiahao = new SpannableString(
											tvNull2.getText());
									// 改变字体颜色
									jiahao.setSpan(
											new ForegroundColorSpan(
													getResources().getColor(
															R.color.tab_top_on)),
											5, 6, 0);
									tvNull2.setText(jiahao);
								} else {
									if (temp.getData().size() > 0) {
										refreshLayout.setVisibility(View.VISIBLE);
										qunZuList.clear();
										qunZuList.addAll(getLastConent(temp
												.getData()));
										pageNo++;
										mAdapter.notifyDataSetChanged();
									}

									
								}
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
							loadfinish = true; // 加载完成
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
						refreshLayout.setRefreshing(false);
						loadfinish = true; // 加载完成
					}
				});
	}

	List<ZoneQunZuBean> getLastConent(List<ZoneQunZuBean> temp) {
		for (ZoneQunZuBean zoneQunZuBean : temp) {
			EMConversation conversation = EMClient.getInstance().chatManager()
					.getConversation(zoneQunZuBean.getHx_group_id());
			if (conversation != null) {
				EMMessage message = conversation.getLastMessage();
				if (message != null) {
					Type type = message.getType();
					if (Type.TXT.equals(type)) {
						EMTextMessageBody body = (EMTextMessageBody) message
								.getBody();
						String msgTxt = body.getMessage();
						zoneQunZuBean.setLastTalk(msgTxt);
					} else if (Type.IMAGE.equals(type)) {
						zoneQunZuBean.setLastTalk("[图片]");
					} else if (Type.VOICE.equals(type)) {
						zoneQunZuBean.setLastTalk("[语音]");
					} else if (Type.LOCATION.equals(type)) {
						zoneQunZuBean.setLastTalk("[位置]");
					}
				}
			}
		}
		return temp;
	}
}
